package com.lzkjiot.service.gnss.transger.core.client;

import com.lzkjiot.service.gnss.transger.core.constants.NettyConstants;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SiNanClientHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            // 处理空闲状态事件
            IdleStateEvent e = (IdleStateEvent) evt;
            if (e.state() == IdleState.ALL_IDLE) {
                // 关闭连接
                String port = ctx.channel().attr(NettyConstants.SERVER_PORT).get();
                ctx.close();
                SiNanClientPoolManager.removeChannel(Integer.valueOf(port));
                log.warn("[TransferClient ChannelHandler] port:{}, tcp disconnected. Cause idle timeout.", port);
            }
        }
    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        String port = ctx.channel().attr(NettyConstants.SERVER_PORT).get();
        ctx.close();
        SiNanClientPoolManager.removeChannel(Integer.valueOf(port));
        log.error("[TransferClient ChannelHandler] port[{}] channel closeed. Cause exption:{}", port, cause.getMessage());
    }
}
